//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.activiti.engine.impl.bpmn.behavior;

import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.delegate.event.ActivitiEventDispatcher;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.bpmn.helper.SkipExpressionUtil;
import org.activiti.engine.impl.calendar.BusinessCalendar;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.cmd.CompleteTaskCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserTaskActivityBehavior extends TaskActivityBehavior {
  private static final long serialVersionUID = 1L;
  private static final Logger LOGGER = LoggerFactory.getLogger(UserTaskActivityBehavior.class);
  protected UserTask userTask;

  public UserTaskActivityBehavior(UserTask userTask) {
    this.userTask = userTask;
  }

  public void execute(DelegateExecution execution) {
    CommandContext commandContext = Context.getCommandContext();
    TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
    TaskEntity task = (TaskEntity)taskEntityManager.create();
    ExecutionEntity executionEntity = (ExecutionEntity)execution;
    task.setExecution(executionEntity);
    task.setTaskDefinitionKey(this.userTask.getId());
    task.setBusinessKey(executionEntity.getProcessInstanceBusinessKey());
    String activeTaskName = null;
    String activeTaskDescription = null;
    String activeTaskDueDate = null;
    String activeTaskPriority = null;
    String activeTaskCategory = null;
    String activeTaskFormKey = null;
    String activeTaskSkipExpression = null;
    String activeTaskAssignee = null;
    String activeTaskOwner = null;
    List<String> activeTaskCandidateUsers = null;
    List<String> activeTaskCandidateGroups = null;
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
    ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
    ObjectNode description;
    if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
      description = Context.getBpmnOverrideElementProperties(this.userTask.getId(), execution.getProcessDefinitionId());
      activeTaskName = this.getActiveValue(this.userTask.getName(), "userTaskName", description);
      activeTaskDescription = this.getActiveValue(this.userTask.getDocumentation(), "userTaskDescription", description);
      activeTaskDueDate = this.getActiveValue(this.userTask.getDueDate(), "userTaskDueDate", description);
      activeTaskPriority = this.getActiveValue(this.userTask.getPriority(), "userTaskPriority", description);
      activeTaskCategory = this.getActiveValue(this.userTask.getCategory(), "userTaskCategory", description);
      activeTaskFormKey = this.getActiveValue(this.userTask.getFormKey(), "userTaskFormKey", description);
      activeTaskSkipExpression = this.getActiveValue(this.userTask.getSkipExpression(), "taskSkipExpression", description);
      activeTaskAssignee = this.getActiveValue(this.userTask.getAssignee(), "userTaskAssignee", description);
      activeTaskOwner = this.getActiveValue(this.userTask.getOwner(), "userTaskOwner", description);
      activeTaskCandidateUsers = this.getActiveValueList(this.userTask.getCandidateUsers(), "userTaskCandidateUsers", description);
      activeTaskCandidateGroups = this.getActiveValueList(this.userTask.getCandidateGroups(), "userTaskCandidateGroups", description);
    } else {
      activeTaskName = this.userTask.getName();
      activeTaskDescription = this.userTask.getDocumentation();
      activeTaskDueDate = this.userTask.getDueDate();
      activeTaskPriority = this.userTask.getPriority();
      activeTaskCategory = this.userTask.getCategory();
      activeTaskFormKey = this.userTask.getFormKey();
      activeTaskSkipExpression = this.userTask.getSkipExpression();
      activeTaskAssignee = this.userTask.getAssignee();
      activeTaskOwner = this.userTask.getOwner();
      activeTaskCandidateUsers = this.userTask.getCandidateUsers();
      activeTaskCandidateGroups = this.userTask.getCandidateGroups();
    }

    String description2;
    if (StringUtils.isNotEmpty(activeTaskName)) {
      description = null;

      try {
        description2 = (String)expressionManager.createExpression(activeTaskName).getValue(execution);
      } catch (ActivitiException var24) {
        description2 = activeTaskName;
        LOGGER.warn("property not found in task name expression " + var24.getMessage());
      }

      task.setName(description2);
    }

    if (StringUtils.isNotEmpty(activeTaskDescription)) {
      description = null;

      try {
        description2 = (String)expressionManager.createExpression(activeTaskDescription).getValue(execution);
      } catch (ActivitiException var23) {
        description2 = activeTaskDescription;
        LOGGER.warn("property not found in task description expression " + var23.getMessage());
      }

      task.setDescription(description2);
    }

    Object formKey;
    if (StringUtils.isNotEmpty(activeTaskDueDate)) {
      formKey = expressionManager.createExpression(activeTaskDueDate).getValue(execution);
      if (formKey != null) {
        if (formKey instanceof Date) {
          task.setDueDate((Date)formKey);
        } else {
          if (!(formKey instanceof String)) {
            throw new ActivitiIllegalArgumentException("Due date expression does not resolve to a Date or Date string: " + activeTaskDueDate);
          }

          String businessCalendarName = null;
          if (StringUtils.isNotEmpty(this.userTask.getBusinessCalendarName())) {
            businessCalendarName = expressionManager.createExpression(this.userTask.getBusinessCalendarName()).getValue(execution).toString();
          } else {
            businessCalendarName = "dueDate";
          }

          BusinessCalendar businessCalendar = Context.getProcessEngineConfiguration().getBusinessCalendarManager().getBusinessCalendar(businessCalendarName);
          task.setDueDate(businessCalendar.resolveDuedate((String)formKey));
        }
      }
    }

    if (StringUtils.isNotEmpty(activeTaskPriority)) {
      formKey = expressionManager.createExpression(activeTaskPriority).getValue(execution);
      if (formKey != null) {
        if (formKey instanceof String) {
          try {
            task.setPriority(Integer.valueOf((String)formKey));
          } catch (NumberFormatException var22) {
            throw new ActivitiIllegalArgumentException("Priority does not resolve to a number: " + formKey, var22);
          }
        } else {
          if (!(formKey instanceof Number)) {
            throw new ActivitiIllegalArgumentException("Priority expression does not resolve to a number: " + activeTaskPriority);
          }

          task.setPriority(((Number)formKey).intValue());
        }
      }
    }

    if (StringUtils.isNotEmpty(activeTaskCategory)) {
      formKey = expressionManager.createExpression(activeTaskCategory).getValue(execution);
      if (formKey != null) {
        if (!(formKey instanceof String)) {
          throw new ActivitiIllegalArgumentException("Category expression does not resolve to a string: " + activeTaskCategory);
        }

        task.setCategory((String)formKey);
      }
    }

    if (StringUtils.isNotEmpty(activeTaskFormKey)) {
      formKey = expressionManager.createExpression(activeTaskFormKey).getValue(execution);
      if (formKey != null) {
        if (!(formKey instanceof String)) {
          throw new ActivitiIllegalArgumentException("FormKey expression does not resolve to a string: " + activeTaskFormKey);
        }

        task.setFormKey((String)formKey);
      }
    }

    task.setAppVersion(executionEntity.getProcessInstance().getAppVersion());
    taskEntityManager.insert(task, executionEntity);
    task.setVariablesLocal(this.calculateInputVariables(execution));
    boolean skipUserTask = false;
    if (StringUtils.isNotEmpty(activeTaskSkipExpression)) {
      Expression skipExpression = expressionManager.createExpression(activeTaskSkipExpression);
      skipUserTask = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression) && SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression);
    }

    if (!skipUserTask) {
      this.handleAssignments(taskEntityManager, activeTaskAssignee, activeTaskOwner, activeTaskCandidateUsers, activeTaskCandidateGroups, task, expressionManager, execution);
    }

    processEngineConfiguration.getListenerNotificationHelper().executeTaskListeners(task, "create");
    if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
      ActivitiEventDispatcher eventDispatcher = Context.getProcessEngineConfiguration().getEventDispatcher();
      eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task));
      if (task.getAssignee() != null) {
        eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
      }
    }

    if (skipUserTask) {
      taskEntityManager.deleteTask(task, (String)null, false, false);
      this.leave(execution);
    }

  }

  protected Map<String, Object> calculateInputVariables(DelegateExecution execution) {
    CommandContext commandContext = Context.getCommandContext();
    return commandContext.getProcessEngineConfiguration().isCopyVariablesToLocalForTasks() ? execution.getVariables() : Collections.emptyMap();
  }

  protected Map<String, Object> calculateOutBoundVariables(DelegateExecution execution, Map<String, Object> taskVariables) {
    CommandContext commandContext = Context.getCommandContext();
    return commandContext.getProcessEngineConfiguration().isCopyVariablesToLocalForTasks() ? taskVariables : Collections.emptyMap();
  }

  public void trigger(DelegateExecution execution, String signalName, Object signalData) {
    CommandContext commandContext = Context.getCommandContext();
    TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
    List<TaskEntity> taskEntities = taskEntityManager.findTasksByExecutionId(execution.getId());
    Iterator var7 = taskEntities.iterator();

    TaskEntity taskEntity;
    do {
      if (!var7.hasNext()) {
        this.propagateVariablesToProcess(execution, commandContext);
        this.leave(execution);
        return;
      }

      taskEntity = (TaskEntity)var7.next();
    } while(taskEntity.isDeleted());

    throw new ActivitiException("UserTask should not be signalled before complete");
  }

  private void propagateVariablesToProcess(DelegateExecution execution, CommandContext commandContext) {
    String processInstanceId = execution.getProcessInstanceId();
    ExecutionEntity processInstanceEntity = processInstanceId != null ? (ExecutionEntity)commandContext.getExecutionEntityManager().findById(processInstanceId) : null;
    if (processInstanceEntity != null) {
      Map<String, Object> taskVariables = new HashMap();
      if (commandContext.getCommand() instanceof CompleteTaskCmd) {
        taskVariables = ((CompleteTaskCmd)commandContext.getCommand()).getTaskVariables();
      }

      Map<String, Object> outboundVariables = this.calculateOutBoundVariables(execution, (Map)taskVariables);
      processInstanceEntity.setVariables(outboundVariables);
    }

  }

  protected void handleAssignments(TaskEntityManager taskEntityManager, String assignee, String owner, List<String> candidateUsers, List<String> candidateGroups, TaskEntity task, ExpressionManager expressionManager, DelegateExecution execution) {
    Object ownerExpressionValue;
    String customGroupIdentityLinkType;
    if (StringUtils.isNotEmpty(assignee)) {
      ownerExpressionValue = expressionManager.createExpression(assignee).getValue(execution);
      customGroupIdentityLinkType = null;
      if (ownerExpressionValue != null) {
        customGroupIdentityLinkType = ownerExpressionValue.toString();
      }

      taskEntityManager.changeTaskAssigneeNoEvents(task, customGroupIdentityLinkType);
    }

    if (StringUtils.isNotEmpty(owner)) {
      ownerExpressionValue = expressionManager.createExpression(owner).getValue(execution);
      customGroupIdentityLinkType = null;
      if (ownerExpressionValue != null) {
        customGroupIdentityLinkType = ownerExpressionValue.toString();
      }

      taskEntityManager.changeTaskOwner(task, customGroupIdentityLinkType);
    }

    Expression userIdExpr;
    Object value;
    List candidates;
    Iterator var18;
    if (candidateGroups != null && !candidateGroups.isEmpty()) {
      var18 = candidateGroups.iterator();

      while(var18.hasNext()) {
        customGroupIdentityLinkType = (String)var18.next();
        userIdExpr = expressionManager.createExpression(customGroupIdentityLinkType);
        value = userIdExpr.getValue(execution);
        if (value instanceof String) {
          candidates = this.extractCandidates((String)value);
          task.addCandidateGroups(candidates);
        } else {
          if (!(value instanceof Collection)) {
            throw new ActivitiIllegalArgumentException("Expression did not resolve to a string or collection of strings");
          }

          task.addCandidateGroups((Collection)value);
        }
      }
    }

    if (candidateUsers != null && !candidateUsers.isEmpty()) {
      var18 = candidateUsers.iterator();

      while(var18.hasNext()) {
        customGroupIdentityLinkType = (String)var18.next();
        userIdExpr = expressionManager.createExpression(customGroupIdentityLinkType);
        value = userIdExpr.getValue(execution);
        if (value instanceof String) {
          candidates = this.extractCandidates((String)value);
          task.addCandidateUsers(candidates);
        } else {
          if (!(value instanceof Collection)) {
            throw new ActivitiException("Expression did not resolve to a string or collection of strings");
          }

          task.addCandidateUsers((Collection)value);
        }
      }
    }

    Object value2;
    Iterator groupIdSet;
    Iterator var16;
    String groupId;
    Iterator var19;
    String groupIdentityLink;
    Expression idExpression;
    List groupIds;
    if (this.userTask.getCustomUserIdentityLinks() != null && !this.userTask.getCustomUserIdentityLinks().isEmpty()) {
      var18 = this.userTask.getCustomUserIdentityLinks().keySet().iterator();

      label135:
      while(var18.hasNext()) {
        customGroupIdentityLinkType = (String)var18.next();
        var19 = ((Set)this.userTask.getCustomUserIdentityLinks().get(customGroupIdentityLinkType)).iterator();

        while(true) {
          while(true) {
            if (!var19.hasNext()) {
              continue label135;
            }

            groupIdentityLink = (String)var19.next();
            idExpression = expressionManager.createExpression(groupIdentityLink);
            value = idExpression.getValue(execution);
            if (value instanceof String) {
              groupIds = this.extractCandidates((String)value);
              var16 = groupIds.iterator();

              while(var16.hasNext()) {
                groupId = (String)var16.next();
                task.addUserIdentityLink(groupId, customGroupIdentityLinkType);
              }
            } else {
              if (!(value instanceof Collection)) {
                throw new ActivitiException("Expression did not resolve to a string or collection of strings");
              }

              groupIdSet = ((Collection)value).iterator();

              while(groupIdSet.hasNext()) {
                task.addUserIdentityLink((String)groupIdSet.next(), customGroupIdentityLinkType);
              }
            }
          }
        }
      }
    }

    if (this.userTask.getCustomGroupIdentityLinks() != null && !this.userTask.getCustomGroupIdentityLinks().isEmpty()) {
      var18 = this.userTask.getCustomGroupIdentityLinks().keySet().iterator();

      label108:
      while(var18.hasNext()) {
        customGroupIdentityLinkType = (String)var18.next();
        var19 = ((Set)this.userTask.getCustomGroupIdentityLinks().get(customGroupIdentityLinkType)).iterator();

        while(true) {
          while(true) {
            if (!var19.hasNext()) {
              continue label108;
            }

            groupIdentityLink = (String)var19.next();
            idExpression = expressionManager.createExpression(groupIdentityLink);
            value = idExpression.getValue(execution);
            if (value instanceof String) {
              groupIds = this.extractCandidates((String)value);
              var16 = groupIds.iterator();

              while(var16.hasNext()) {
                groupId = (String)var16.next();
                task.addGroupIdentityLink(groupId, customGroupIdentityLinkType);
              }
            } else {
              if (!(value instanceof Collection)) {
                throw new ActivitiException("Expression did not resolve to a string or collection of strings");
              }

              groupIdSet = ((Collection)value).iterator();

              while(groupIdSet.hasNext()) {
                task.addGroupIdentityLink((String)groupIdSet.next(), customGroupIdentityLinkType);
              }
            }
          }
        }
      }
    }

  }

  protected List<String> extractCandidates(String str) {
    return Arrays.asList(str.split("[\\s]*,[\\s]*"));
  }
}
